<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\TCourseSigninInfo;
use app\models\TCourseSigninStudent;
use app\common\ArrayHelper;
use app\models\TCourseMember;
use app\models\TCourseInfo;
use app\models\TCourseEvaluate;
use Faker\Provider\Uuid;
use app\common\PdUtils;
use app\models\TBaseUserProfile;

class ClassroomController extends Controller{
    public $enableCsrfValidation = false;
    public function init()
    {
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }
    /**
     * 微信小程序获取课表列表接口
     * @param string userId:用户ID
     * @return mixed 错误返回json，正确返回json
     * @date: 2020-03-04
     * @author: gyq
     */
    public function actionAppGetScheduleList(){
        $error = array();
        $userId = isset($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[]=array('用户ID不能为空');
        $time = isset($_REQUEST['time']) ? $_REQUEST['time'] : date('Y-m-d',time());
        if(!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            //一年内有课表的日期集合
            $startdate = (date('Y')-1).'-'.date('m-d');
            $enddate = (date('Y')+1).'-'.date('m-d');
            $date = self::getDateFromRange($startdate,$enddate);
            $new_array = [];
            foreach($date as $k=>$v){
                $times=self::getTime(strtotime($v));
                $sql = "SELECT b.id FROM t_course_member a LEFT JOIN t_course_schedule b ON a.course_id=b.t_course_id WHERE a.user_id=:userId AND UNIX_TIMESTAMP(b.begin_time) BETWEEN :star AND :ends AND a.del_flag=0 AND b.del_flag=0";
                $corseList = Yii::$app->db->createCommand($sql)->bindValues([':userId'=>$userId,':star'=>$times['star'],':ends'=>$times['end']])->queryOne();
                if ($corseList) {
                    $new_array[]['date']=$v;
                }
            }
            $d_time = self::getTime(strtotime($time));
            $sql = "SELECT 
b.id,
b.schedule_name,
b.t_course_id,
i.name as course_name,
i.b_course_info_id,
i.project_id,
b.begin_time,
c.t_course_item_id,
c.t_course_item_pid 
FROM t_course_member a 
LEFT JOIN t_course_schedule b ON a.course_id=b.t_course_id
LEFT JOIN t_course_info i ON b.t_course_id=i.id
LEFT JOIN t_course_schedule_chapter c ON c.t_course_schedule_id=b.id
WHERE 
a.user_id=:userId 
AND UNIX_TIMESTAMP(b.begin_time) 
BETWEEN :star 
AND :ends 
AND a.del_flag=0 
AND b.del_flag=0 
ORDER BY b.begin_time ASC";
            $scheduleList = Yii::$app->db->createCommand($sql)->bindValues([':userId'=>$userId,':star'=>$d_time['star'],':ends'=>$d_time['end']])->queryAll();
            if($scheduleList){
                foreach($scheduleList as $k=>&$v){
                    $sql="select title from t_course_item where id='".$v['t_course_item_pid']."'";
                    $chapter = \Yii::$app->db->createCommand($sql)->queryScalar();
                    $sql="select title from t_course_item where id='".$v['t_course_item_id']."'";
                    $jie = \Yii::$app->db->createCommand($sql)->queryScalar();
                    $chapter_str = $chapter.'>>'.$jie;
                    $v['zhang_jie']=$chapter_str;
                    //班级名称
                    $sql="SELECT
	c.class_name
FROM
	t_base_class c
LEFT JOIN t_course_schedule_class sc ON sc.class_id = c.id
WHERE
	sc.t_course_schedule_id =:schedule_id";
                    $classInfo=\yii::$app->db->createCommand($sql)->bindValues([':schedule_id'=>$v['id']])->queryAll();
                    $str="";
                    foreach($classInfo as $key=>$value){
                        $str.=$value['class_name'].",";
                    }
                    $v['class_name']=rtrim($str,',');
                }
                $data['existenceSchedule'] = $new_array;
                $data['todayslesson'] = $scheduleList;
                $data['nowTime']=date('Y-m-d',time());
                $result = [
                    'msg' => '查询成功',
                    'ver' => '1.5.0',
                    'data' => $data,
                    'code' => '200'
                ];
            }else{
                $result = [
                    'msg' => '没有查询到相关数据',
                    'ver' => '1.5.0',
                    'data' => ['existenceSchedule'=>$new_array,'todayslesson'=>[],'nowTime'=>date('Y-m-d',time())],
                    'code' => '200'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序课程预习复习列表接口
     * @param int  courseId:课程ID userId:用户ID projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-03-04
     * @author: gyq
     */
    public function actionAppGetScheduleInfo()
    {
        $error = array();
        $tcourseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $scheduleId = !empty($_REQUEST['scheduleId'])?$_REQUEST['scheduleId']:$error[]=array('ID不能为空');
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $type = !empty($_REQUEST['type'])?$_REQUEST['type']:$error[]=array('类型不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $info_arr= array();
            $sql="select tcsr.resource_id as id,tcsr.item_id,c.title,tcsr.file_id,trf.uri,trf.type as file_type,tcsr.create_time,tcsr.times,trf.mime as mime_type from t_course_schedule_resource tcsr left join t_resource_file trf on trf.id=tcsr.file_id left join t_course_item_resource_reference c on c.resourse_id=tcsr.resource_id and c.item_id=tcsr.item_id where tcsr.t_course_schedule_id=:scheduleId and tcsr.t_course_id=:courseId and tcsr.type=:type";
            $resourceList = \Yii::$app->db->createCommand($sql)
                ->bindValue(':scheduleId', $scheduleId)
                ->bindValue(':courseId', $tcourseId)
                ->bindValue(':type', $type)
                ->queryAll();

            foreach ($resourceList as $k=>&$resource)
            {
                    if(in_array($resource['mime_type'],['resourceType.document','resourceType.ppt'])){
                        $resource['docConvert']=true;
                        $fileBaseUrl = \Yii::$app->params['fileUrlWeiXin'];
                        $resource['uri']=$fileBaseUrl.(empty($resource)?'':$resource['uri']);
                    }else{
                        $resource['docConvert']=false;
                        $resource['uri']=\yii::$app->params['fileUrlWeiXin'].$resource['uri'];
                    }
                $sql="select current_progress,type from t_course_items_video_current where item_id=:itemId and resource_id=:resourceId and user_id=:userId and del_flag=0";
                $info=\yii::$app->db->createCommand($sql)->bindValues([
                    ':itemId'=>$resource['item_id'],
                    ':resourceId'=>$resource['id'],
                    ':userId'=>$userId,
                ])->queryOne();
                if($info['type']=='progressType.video'){
                    $sql="SELECT
	trf.play_time
FROM
	t_resource_file trf
LEFT JOIN t_resource_info tri ON trf.id = tri.file_id
WHERE
	tri.id =:resourceId";
                    $play_time=\yii::$app->db->createCommand($sql)->bindValues([':resourceId'=>$resource['id']])->queryScalar();
                    $t = explode(':',$play_time);
                    $totalTime=$t[0] * 3600 + $t[1]*60+$t[2];//假定最长视频十二小时
                    $progress=round(($info['current_progress']/$totalTime)*100);
                }else{
                    //非视频音频类型
                    $progress=empty($info['current_progress']) ? 0 : 100 ;
                }
                //进度不能大于100
                $progress=($progress>100)?100:$progress;
                if(in_array($resource['file_type'],['doc','docx'])){
                    $icon="/weixin/resources/01.png";
                }elseif(in_array($resource['file_type'],['png','jpg','jpeg','JPG','PNG','JPEG','bmp','gif'])){
                    $icon="/weixin/resources/02.png";
                }elseif(in_array($resource['file_type'],['xls','xlsx'])){
                    $icon="/weixin/resources/03.png";
                }elseif($resource['file_type']=='pdf'){
                    $icon="/weixin/resources/04.png";
                }elseif($resource['file_type']=='txt'){
                    $icon="/weixin/resources/05.png";
                }elseif(in_array($resource['file_type'],['ppt','pptx'])){
                    $icon="/weixin/resources/06.png";
                }elseif($resource['file_type']=='swf'){
                    $icon="/weixin/resources/07.png";
                }elseif(in_array($resource['file_type'],['html','htm'])){
                    $icon="/weixin/resources/08.png";
                }elseif(in_array($resource['file_type'],['ogg','ogv','mov','webm','mp3','wav','mid'])){
                    $icon="/weixin/resources/09.png";
                }else if(in_array($resource['file_type'],['flv','mkv','avi','rm','rmvb','mp4','wmv'])){
                    $icon="/weixin/resources/10.png";
                }else{
                    $icon="/weixin/resources/11.png";
                }
                $resource['icon']=\yii::$app->params['interFaceWeiXin'].$icon;
                $resource['progress']=$progress;
                $info_arr[]= $resource;
            }
            if($info_arr)
            {
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $info_arr,
                    'success' => true,
                    'code' => '200'
                ];
            }
            elseif(empty($info_arr))
            {
                $result = [
                    'msg' => '没有查询到相关数据',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '200'
                ];
            }
            elseif($info_arr===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序获取签到事件接口
     * @param int  party_id:班级ID course_id:课程ID user_id:用户ID  projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-03-04
     * @author: gyq
     */
    public function actionAppGetSigninInfo()
    {
        $error = array();
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error=array('用户id不能为空');
        $courseId = !empty($_REQUEST['courseId'])?$_REQUEST['courseId']:$error=array('课程id不能为空');
        $scheduleId = !empty($_REQUEST['scheduleId'])?$_REQUEST['scheduleId']:$error=array('课表id不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $sql = "SELECT tcsi.id,tcsi.code,tcsi.start_time,tcsi.end_time,tcsi.old_id,tcss.status,tcss.code as student_code,tcss.signin_time
FROM t_course_signin_info tcsi 
LEFT JOIN t_course_signin_student tcss ON tcsi.id=tcss.sign_id
LEFT JOIN t_course_schedule_sign ss ON ss.sign_id=tcsi.id
WHERE tcsi.course_id=:courseId 
AND tcss.user_id=:userId 
AND tcsi.status=:status 
AND '".time()."' 
BETWEEN UNIX_TIMESTAMP(tcsi.start_time) 
AND UNIX_TIMESTAMP(tcsi.end_time) 
AND tcsi.type='signinType.common' 
AND tcsi.del_flag=0 
AND tcss.del_flag=0 
AND ss.del_flag=0
AND ss.t_course_schedule_id=:scheduleId
ORDER BY tcsi.create_time DESC limit 1";
            $params = [':courseId' => $courseId,':userId' => $userId,':status' => 'usingStatus.start',':scheduleId'=>$scheduleId];
            $sign = Yii::$app->db->createCommand($sql)
                ->bindValues($params)
                ->queryOne();
            //当前时间年月日星期
            $year=date('Y',time());
            $month=date('m',time());
            $day=date('d',time());
            $week=date('w',time());
            $weekarray=array("日","一","二","三","四","五","六");
            $timeInfo=['year'=>$year,'month'=>$month,'day'=>$day,'week'=>"星期".$weekarray[$week]];
            if($sign)
            {
                $sign['timeInfo']=$timeInfo;
                //处理学生签到码
                if(!empty($sign['student_code']) && $sign['status']=='yesOrNo.yes'){
                        $first=substr($sign['student_code'],0,1);
                        $second=substr($sign['student_code'],1,1);
                        $third=substr($sign['student_code'],2,1);
                        $last=substr($sign['student_code'],3,1);
                        $sign['student_code']=[
                            empty($first)&&$first!=0? '':$first,
                            empty($second)&&$second!=0? '':$second,
                            empty($third)&&$third!=0? '':$third,
                            empty($last)&&$last!=0? '':$last
                        ];
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $sign,
                    'success' => true,
                    'code' => '200'
                ];
            }
            elseif(empty($sign))
            {
                $result = [
                    'msg' => '已结束',
                    'ver' => '1.5.0',
                    'data' => ['id' => '','code' => '','start_time'=>'','end_time' => '','timeInfo'=>$timeInfo,'signin_time'=>''],
                    'success' => false,
                    'code' => '200'
                ];
            }
            elseif($sign===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => ['id' => '','code' => '','start_time'=>'','end_time' => '','timeInfo'=>$timeInfo],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序学生签到接口
     * @param int  userId:用户ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-03-05
     * @author: gyq
     */
    public function actionAppDoSigninInfo()
    {
        $error = array();
        $sign_id = isset($_REQUEST['signId'])?$_REQUEST['signId']:$error[]=array('签到事件ID不能为空');
        $code = isset($_REQUEST['code'])?$_REQUEST['code']:$error[]=array('签到码不能为空');
        $user_id = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $sign = TCourseSigninInfo::find()->where('id=:sign_id and del_flag=0',[':sign_id'=>$sign_id])->one();
            if($sign)
            {
                $time = date("Y-m-d H:i:s",time());
                if($time > $sign->end_time || $time < $sign->start_time)
                {
                    $result = [
                        'msg' => '未在签到时间内',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '400'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                $model = TCourseSigninStudent::find()->where('sign_id=:sid and user_id=:uid and del_flag=0',[':sid'=>$sign_id,':uid'=>$user_id])->one();
                if (empty($model)) {
                    $result = [
                        'msg' => '没有该签到事件',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '404'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                $model->status = "yesOrNo.yes";
                $model->code = $code;
                $model->signin_time = date('Y-m-d H:i:s');
                $model->student_status = 'signinStatus.sign';
                $model->update_by = $user_id;
                $model->update_time = date('Y-m-d H:i:s');
                $res = $model->update();
                if($res)
                {
                    $first=substr($code,0,1);
                    $second=substr($code,1,1);
                    $third=substr($code,2,1);
                    $last=substr($code,3,1);
                    $student_code=[
                        empty($first)&&$first!=0? '':$first,
                        empty($second)&&$second!=0? '':$second,
                        empty($third)&&$third!=0? '':$third,
                        empty($last)&&$last!=0? '':$last
                        ];
                    $result = [
                        'msg' => '签到成功',
                        'ver' => '1.5.0',
                        'data' => ['signin_time'=>date('Y-m-d H:i:s'),'student_code'=>$student_code],
                        'success' => true,
                        'code' => '200'
                    ];
                }
                else
                {
                    $result = [
                        'msg' => '签到失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'success' => false,
                        'code' => '400'
                    ];
                }
            }
            else
            {
                $result = [
                    'msg' => '没有该签到事件',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 获取今天的开始和结束时间
     * @return mixed
     */
    public static function getTime($time){
        $str=date("Y-m-d",$time)." 0:0:0";
        $data["star"]=strtotime($str);
        $str=date("Y-m-d",$time)." 24:00:00";
        $data["end"]=strtotime($str);
        return $data;
    }
    public static function get_week($time = '', $format='d'){
        $time = $time != '' ? $time : time();
        //获取当前周几
        $week = date('w', $time);
        $str = date('d', $time);
        for ($i=1; $i<=7; $i++){
            $str.= ','.date($format ,strtotime( '+' . $i-$week .' days', $time));
        }
        return trim($str,',');
    }
    /**
     * 获取指定日期段内每一天的日期
     * @param  Date  $startdate 开始日期
     * @param  Date  $enddate   结束日期
     * @return Array
     */

    public static  function  getDateFromRange($startdate, $enddate){
    $stimestamp = strtotime($startdate);
    $etimestamp = strtotime($enddate);

    // 计算日期段内有多少天
    $days = ($etimestamp-$stimestamp)/86400+1;
    // 保存每天日期
    $date = array();

    for($i=0; $i<$days; $i++){
        $date[] = date('Y-m-d', $stimestamp+(86400*$i));
    }
    return $date;
}
    /**
     * 微信小程序签到列表接口
     * @param int  userId:用户ID status:状态 token:token projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-4-15
     * @author: gyq
     */
    public function actionAppSignList(){
        $error 		= array();
        $userId     = isset($_REQUEST['userId']) && !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[]=array('用户ID不能为空');
        $courseId 	= isset($_REQUEST['courseId']) && !empty($_REQUEST['courseId']) ? $_REQUEST['courseId'] : '';
        $status 	= isset($_REQUEST['status']) && !empty($_REQUEST['status']) ? $_REQUEST['status'] : $error[]=array('状态不能为空');
        $projectId 	= isset($_REQUEST['projectId']) && !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[]=array('联盟ID不能为空');
        $pageSize 	= isset($_REQUEST['pageSize'])?$_REQUEST['pageSize']:'10';
        $page 		= isset($_REQUEST['page'])?$_REQUEST['page']:'1';
        $limit 		= "limit ".($page-1)*$pageSize.",$pageSize";
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $and = '';
            if (strlen($courseId)>0) {
                $and = " AND a.course_id='".$courseId."'";
            }
            $sql = "";
            if ($status=='signinType.unpublish') {
                $sql = "SELECT a.id,a.course_id,a.start_time,a.end_time,a.type,a.code,IFNULL(tbc.class_name,'默认班级') as class_name,'".$status."' as status,a.old_id,b.class_id "
                    . "FROM t_course_signin_info a "
                    . "LEFT JOIN t_base_class tbc ON FIND_IN_SET(tbc.id,a.party_id) "
                    . "LEFT JOIN t_course_member b ON b.course_id=a.course_id AND b.class_id=tbc.id "
                    . "WHERE a.create_by=:userId AND a.del_flag=0 AND a.publishStatus=0 AND b.del_flag=0 $and GROUP BY a.id,tbc.id ORDER BY a.create_time DESC $limit";
            }
            if ($status=='signinType.ongoing') {
                // $where = " AND a.publishStatus=1 AND '".time()."' BETWEEN UNIX_TIMESTAMP(a.start_time) AND UNIX_TIMESTAMP(a.end_time)";
                $sql = "SELECT a.id,a.course_id,a.start_time,a.end_time,a.type,a.code,IFNULL(tbc.class_name,'默认班级') as class_name,'".$status."' as status,a.old_id,c.class_id "
                    . "FROM t_course_signin_info a "
                    . "LEFT JOIN t_course_signin_student b ON a.id=b.sign_id "
                    . "LEFT JOIN t_course_member c ON b.user_id=c.user_id AND a.course_id=c.course_id "
                    . "LEFT JOIN t_base_class tbc ON tbc.id=c.class_id "
                    . "WHERE b.create_by=:userId AND a.del_flag=0 AND b.del_flag=0 AND c.del_flag=0 AND a.publishStatus=1 AND '".time()."' < UNIX_TIMESTAMP(a.end_time) $and GROUP BY a.id,c.class_id ORDER BY b.create_time DESC $limit";
            }
            if ($status=='signinType.over') {
                // $where = " AND '".time()."' > UNIX_TIMESTAMP(a.end_time)";
                $sql = "SELECT a.id,a.course_id,a.start_time,a.end_time,a.type,a.code,IFNULL(tbc.class_name,'默认班级') as class_name,'".$status."' as status,a.old_id,c.class_id "
                    . "FROM t_course_signin_info a "
                    . "LEFT JOIN t_course_signin_student b ON a.id=b.sign_id "
                    . "LEFT JOIN t_course_member c ON b.user_id=c.user_id AND a.course_id=c.course_id "
                    . "LEFT JOIN t_base_class tbc ON tbc.id=c.class_id "
                    . "WHERE b.create_by=:userId AND a.del_flag=0 AND b.del_flag=0 AND c.del_flag=0 AND '".time()."' > UNIX_TIMESTAMP(a.end_time) $and GROUP BY a.id,c.class_id ORDER BY b.create_time DESC $limit";
            }
            $signList = Yii::$app->db->createCommand($sql)->bindValues(['userId'=>$userId])->queryAll();
            if ($signList) {
                foreach ($signList as $key => $value) {
                    if ($value['type']=='signinType.code') {
                        $send_data = [
                            'type' => 'qrType.signin',
                            'id' => $value['id']
                        ];
                        $param_url = http_build_query($send_data,'','%26');
                        $qr_url = 'http://wzk.36ve.com/index.php'.DIRECTORY_SEPARATOR.'home'.DIRECTORY_SEPARATOR.'qrcode?'.$param_url;
                        $url = PdUtils::get_qr_code_image_url($qr_url,400,400);
                        $signList[$key]['code'] = $url;
                    }
                }
                $result = [
                    'msg' => '查询成功',
                    'ver' => '1.5.0',
                    'data' => $signList,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '暂无内容',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序签到详情接口（暂未使用）
     * @param int  class_id:班级ID course_id:课程ID user_id:用户ID token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-4-15
     * @author: gyq
     */
    public function actionAppSignInfo(){
        $error 		= array();
        $sign_id 	= isset($_REQUEST['sign_id']) && !empty($_REQUEST['sign_id']) ? $_REQUEST['sign_id'] : $error=array('签到id不能为空');
        $course_id  = isset($_REQUEST['course_id']) && !empty($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error=array('课程id不能为空');
        $class_id 	= isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : $error=array('班级id不能为空');
        $status 	= isset($_REQUEST['status']) && !empty($_REQUEST['status']) ? $_REQUEST['status'] : $error=array('签到状态不能为空');
        $projectId 	= isset($_REQUEST['projectId']) && !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[]=array('联盟ID不能为空');
        $pageSize   = !empty($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : '20';
        $page       = !empty($_REQUEST['page']) ? $_REQUEST['page'] : '1';
        $limit      = "limit ".($page-1)*$pageSize.",$pageSize";
        if (!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $where = '';
            if ($status=='yesOrNo.yes') {
                $where = " AND a.student_status='signinStatus.sign' ";
            } else {
                $where = " AND a.student_status!='signinStatus.sign' ";
            }
            $sign_sql = "SELECT count(*) "
                . "FROM t_course_signin_student a "
                . "LEFT JOIN t_course_member c ON a.user_id = c.user_id and c.course_id='".$course_id."' "
                . "WHERE c.del_flag=0 AND c.class_id=:class_id and a.del_flag=0 AND a.sign_id=:sign_id AND a.student_status='signinStatus.sign' ";
            $sign_num = Yii::$app->db->createCommand($sign_sql)->bindValues([':sign_id'=>$sign_id,':class_id'=>$class_id])->queryScalar();
            $unsign_sql = "SELECT count(*) "
                . "FROM t_course_signin_student a "
                . "LEFT JOIN t_course_member c ON a.user_id = c.user_id and c.course_id='".$course_id."' "
                . "WHERE c.del_flag=0 AND c.class_id=:class_id and a.del_flag=0 AND a.sign_id=:sign_id AND a.student_status!='signinStatus.sign' ";
            $unsign_num = Yii::$app->db->createCommand($unsign_sql)->bindValues([':sign_id'=>$sign_id,':class_id'=>$class_id])->queryScalar();
            //没有过滤删除的班级
            $sql = "SELECT a.id as sign_id,a.user_id,b.pet_name,c.class_id,IFNULL(d.class_name,'默认班级') as class_name,a.signin_time,a.student_status "
                . "FROM t_course_signin_student a "
                . "LEFT JOIN t_base_user_profile b ON a.user_id = b.user_id "
                . "LEFT JOIN t_course_member c ON a.user_id = c.user_id and c.course_id='".$course_id."' "
                . "LEFT JOIN t_base_class d ON c.class_id = d.id "
                . "WHERE c.del_flag=0 AND c.class_id=:class_id and a.del_flag=0 AND a.sign_id=:sign_id $where GROUP BY a.user_id "
                . "ORDER BY a.signin_time DESC,class_name DESC $limit";
            $student = Yii::$app->db->createCommand($sql)->bindValues([':sign_id'=>$sign_id,':class_id'=>$class_id])->queryAll();
            $new_array = array('sign_num'=>$sign_num,'unsign_num'=>$unsign_num,'data'=>$student);
            if (!empty($student)) {
                $result = [
                    'msg' => '查询成功',
                    'ver' => '1.5.0',
                    'data' => $new_array,
                    'code' => '200'
                ];
            } else {
                $result = [
                    'msg' => '暂无内容',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序保存并发布签到接口
     * @param int  class_id:班级ID course_id:课程ID user_id:用户ID token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-4-15
     * @author: gyq
     */
    public function actionAppPublishSign(){
        $error 		= array();
        $class_id 	= isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : $error=array('班级id不能为空');
        $course_id 	= isset($_REQUEST['course_id']) && !empty($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error=array('课程id不能为空');
        $user_id 	= isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : $error=array('用户id不能为空');
        $sign_type 	= isset($_REQUEST['sign_type']) && !empty($_REQUEST['sign_type']) ? $_REQUEST['sign_type'] : $error=array('签到类型不能为空');
        $start_time = isset($_REQUEST['start_time']) && !empty($_REQUEST['start_time']) ? $_REQUEST['start_time'] : $error=array('开始时间不能为空');
        $end_time 	= isset($_REQUEST['end_time']) && !empty($_REQUEST['end_time']) ? $_REQUEST['end_time'] : $error=array('结束时间不能为空');
        $projectId 	= isset($_REQUEST['projectId']) && !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[]=array('联盟ID不能为空');
        if (!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $this->CheckClass($class_id,$course_id,$start_time,'','签到开始时间不能重叠');
            $this->CheckClass($class_id,$course_id,$start_time,$end_time,'签到结束时间不能重叠');
            $chars_array = array(
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
            );
            $charsLen = count($chars_array) - 1;

            $code = "";
            if ($sign_type=='signinType.common') {
                for ($i=0; $i<4; $i++) {
                    $code .= $chars_array[mt_rand(0, $charsLen)];
                }
            } else {
                $code = '0000';
            }
            $major_id = TBaseUserProfile::find()->where('user_id=:userId and del_flag=0',[':userId'=>$user_id])->one()->major_id;
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $model = new TCourseSigninInfo();
                $model->id = Uuid::uuid();
                $model->party_id = $class_id;
                $model->course_id = $course_id;
                $model->user_id = $user_id;
                $model->major_id = $major_id;
                $model->start_time = $start_time;
                $model->end_time = $end_time;
                $model->code = $code;
                $model->type = $sign_type;
                $model->is_location = '0';
                $model->publishStatus = 1;
                $model->create_by = $user_id;
                $model->create_time = date("Y-m-d H:i:s",time());
                $model->del_flag = 0;
                $model->status = 'usingStatus.start';
                $model->old_id = $model->id;
                if ($model->validate() && $model->save()){
                    $class_ids = explode(',', trim($class_id, ','));
                    $signModel = new TCourseSigninStudent();
                    $flag = true;
                    for($i=0;$i<count($class_ids);$i++){
                        $sql = "SELECT distinct(a.user_id) FROM t_course_member a LEFT JOIN t_base_user b ON a.user_id=b.id WHERE a.class_id=:class_id AND a.course_id=:course_id AND a.del_flag=0 AND b.del_flag=0";
                        $student = Yii::$app->db->createCommand($sql)->bindValues([':class_id'=>$class_ids[$i],':course_id'=>$course_id])->queryAll();
                        foreach ($student as $key => $val) {
                            $signStudent = clone $signModel;
                            $signStudent->id = Uuid::uuid();
                            $signStudent->sign_id = $model->id;
                            $signStudent->user_id = $val['user_id'];
                            $signStudent->status = 'yesOrNo.no';
                            $signStudent->major_id = $major_id;
                            $signStudent->student_status = "signinStatus.default";
                            $signStudent->del_flag = 0;
                            $signStudent->create_by = $user_id;
                            $signStudent->create_time = date('Y-m-d H:i:s',time());
                            $res = $signStudent->save(false);
                            if ($res != false) {
                                $flag = true;
                            } else {
                                $flag = false;
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $url = '';
                        if ($sign_type=='signinType.code') {
                            $send_data = [
                                'type' => 'qrType.signin',
                                'id' => $model->id
                            ];
                            $param_url = http_build_query($send_data,'','%26');
                            $qr_url = 'http://wzk.36ve.com/index.php'.DIRECTORY_SEPARATOR.'home'.DIRECTORY_SEPARATOR.'qrcode?'.$param_url;
                            $url = PdUtils::get_qr_code_image_url($qr_url,400,400);
                        }
                        $res_data = [
                            'id' => $model->id,
                            'sign_type' => $sign_type,
                            'code' => $sign_type=='signinType.code' ? $url : $code
                        ];
                        $transaction->commit();
                        $result = [
                            "msg" => "发布成功",
                            "ver" => "1.5.0",
                            'data' => $res_data,
                            'code'=>'200'
                        ];
                    } else {
                        $transaction->rollback();
                        $result = [
                            "msg"=> "发布失败",
                            "ver"=> "1.5.0",
                            'data'=>array(),
                            'code'=>'400'
                        ];
                    }
                } else {
                    $transaction->rollback();
                    $result = [
                        "msg"=> "发布失败",
                        "ver"=> "1.5.0",
                        'data'=>array(),
                        'code'=>'400'
                    ];
                }
                Yii::$app->end(json_encode($result));
            } catch (Exception $e) {
                $result = [
                    "msg" => "发布失败",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }
    /**
     * 微信小程序保存签到接口
     * @param int  class_id:班级ID course_id:课程ID user_id:用户ID token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-4-15
     * @author: gyq
     */
    public function actionAppSaveSignInfo(){
        $error      = array();
        $class_id   = isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : $error=array('班级id不能为空');
        $course_id  = isset($_REQUEST['course_id']) && !empty($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error=array('课程id不能为空');
        $user_id    = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : $error=array('用户id不能为空');
        $sign_type  = isset($_REQUEST['sign_type']) && !empty($_REQUEST['sign_type']) ? $_REQUEST['sign_type'] : $error=array('签到类型不能为空');
        $start_time = isset($_REQUEST['start_time']) && !empty($_REQUEST['start_time']) ? $_REQUEST['start_time'] : $error=array('开始时间不能为空');
        $end_time   = isset($_REQUEST['end_time']) && !empty($_REQUEST['end_time']) ? $_REQUEST['end_time'] : $error=array('结束时间不能为空');
        $projectId  = isset($_REQUEST['projectId']) && !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[]=array('联盟ID不能为空');
        if (!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => (object)[],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $this->CheckClass($class_id,$course_id,$start_time,'','签到开始时间不能重叠');
            $this->CheckClass($class_id,$course_id,$start_time,$end_time,'签到结束时间不能重叠');
            $chars_array = array(
                "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
            );
            $charsLen = count($chars_array) - 1;

            $code = "";
            if ($sign_type=='signinType.common') {
                for ($i=0; $i<4; $i++) {
                    $code .= $chars_array[mt_rand(0, $charsLen)];
                }
            } else {
                $code = '0000';
            }
            $major_id = TBaseUserProfile::find()->where('user_id=:userId and del_flag=0',[':userId'=>$user_id])->one()->major_id;
            $model = new TCourseSigninInfo();
            $model->id = Uuid::uuid();
            $model->party_id = $class_id;
            $model->course_id = $course_id;
            $model->user_id = $user_id;
            $model->major_id = $major_id;
            $model->start_time = $start_time;
            $model->end_time = $end_time;
            $model->code = $code;
            $model->type = $sign_type;
            $model->is_location = '0';
            $model->publishStatus = 0;
            $model->create_by = $user_id;
            $model->create_time = date("Y-m-d H:i:s",time());
            $model->del_flag = 0;
            $model->status = 'usingStatus.start';
            $model->old_id = $model->id;
            if ($model->validate() && $model->save()){
                $result = [
                    "msg" => "保存成功",
                    "ver" => "1.5.0",
                    'data' => ['sign_id'=>$model->id],
                    'code'=>'200'
                ];
            } else {
                $result = [
                    "msg"=> "保存失败",
                    "ver"=> "1.5.0",
                    'data'=> (object)[],
                    'code'=>'400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序签到修改学生状态接口
     * @param int  signId:签到ID status:签到状态 userId:用户ID token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-4-15
     * @author: gyq
     */
    public function actionAppEditSignStatus(){
        $error      = array();
        $signId     = isset($_REQUEST['signId']) && !empty($_REQUEST['signId']) ? $_REQUEST['signId'] : $error=array('签到id不能为空');
        $userId     = isset($_REQUEST['userId']) && !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error=array('用户id不能为空');
        $status     = isset($_REQUEST['status']) && !empty($_REQUEST['status']) ? $_REQUEST['status'] : $error=array('签到状态不能为空');
        $projectId  = isset($_REQUEST['projectId']) && !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[]=array('联盟ID不能为空');
        if (!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $time = date('Y-m-d H:i:s');
            $model = TCourseSigninStudent::find()->where('id=:sid',[':sid'=>$signId])->one();
            $model->status = "yesOrNo.yes";
            $model->signin_time = date('Y-m-d H:i:s');
            $model->student_status = $status;
            $model->sign_person_type = 1;
            $model->update_by = $userId;
            $model->update_time = $time;
            $res = $model->update();
            if($res !=false){
                $result = array(
                    "msg"=> "操作成功",
                    "ver"=> "1.5.0",
                    'data'=>array(),
                    'code'=>'200'
                );
            } else {
                $result = array(
                    "msg"=> "操作失败",
                    "ver"=> "1.5.0",
                    'data'=>array(),
                    'code'=>'400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序发布签到接口
     * @param int  signId:签到ID courseId:课程ID userId:用户ID token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-4-15
     * @author: gyq
     */
    public function actionAppPublishSignInfo(){
        $error      = array();
        $courseId   = isset($_REQUEST['courseId']) && !empty($_REQUEST['courseId']) ? $_REQUEST['courseId'] : $error=array('课程id不能为空');
        $signId     = isset($_REQUEST['signId']) && !empty($_REQUEST['signId']) ? $_REQUEST['signId'] : $error=array('签到id不能为空');
        $userId     = isset($_REQUEST['userId']) && !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error=array('用户id不能为空');
        $projectId  = isset($_REQUEST['projectId']) && !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[]=array('联盟ID不能为空');
        if (!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $TCourseSigninInfo = \app\models\TCourseSigninInfo::find()->where(['id'=>$signId,'course_id'=>$courseId,'del_flag'=>0])->asArray()->one();
            $major_id = TBaseUserProfile::find()->where('user_id=:userId and del_flag=0',[':userId'=>$userId])->one()->major_id;
            $class_id = $TCourseSigninInfo['party_id'];
            $time = date('Y-m-d H:i:s');
            $flag = false;
            if ($TCourseSigninInfo['publishStatus']==0) {
                $transaction = Yii::$app->db->beginTransaction();
                // $res_sign = \app\models\TCourseSigninInfo::updateAll(['publishStatus'=>1,'update_by'=>$userId,'update_time'=>$time],['id'=>$signId,'course_id'=>$courseId,'del_flag'=>0]);
                $res_sign =Yii::$app->db->createCommand()->update('t_course_signin_info', ['publishStatus' => 1,'update_by'=>$userId,'update_time'=>$time], 'id=:id and del_flag=0', [':id'=>$signId])->execute();
                $class_ids = explode(',', trim($class_id, ','));
                $stuModel = new TCourseSigninStudent();
                TCourseSigninStudent::updateAll(['del_flag'=>1],['sign_id'=>$signId]);
                $sign_student = [];
                for ($i=0;$i<count($class_ids);$i++) {
                    $sql = "SELECT distinct(a.user_id) FROM t_course_member a LEFT JOIN t_base_user b ON a.user_id=b.id WHERE a.class_id=:class_id AND a.course_id='$courseId' AND a.del_flag=0 AND b.del_flag=0";
                    $student = Yii::$app->db->createCommand($sql)->bindValue(':class_id', $class_ids[$i])->queryAll();
                    foreach ($student as $st) {
                        $stu_data = clone  $stuModel;
                        $stu_data->id = Uuid::uuid();
                        $stu_data->sign_id = $signId;
                        $stu_data->status = 'yesOrNo.no';
                        $stu_data->user_id = $st['user_id'];
                        $stu_data->major_id = $major_id;
                        $stu_data->student_status = "signinStatus.default";
                        $stu_data->del_flag = 0;
                        $stu_data->create_by = $userId;
                        $stu_data->create_time = date('Y-m-d H:i:s');
                        if ($stu_data->save()) {
                            $flag = true;
                        } else {
                            $flag = false;
                            break;
                        }
                    }
                }
                if ($flag) {
                    $url = '';
                    if ($TCourseSigninInfo['type']=='signinType.code') {
                        $send_data = [
                            'type' => 'qrType.signin',
                            'id' => $signId
                        ];
                        $param_url = http_build_query($send_data,'','%26');
                        $qr_url = Yii::$app->request->hostInfo.Yii::$app->homeUrl.DIRECTORY_SEPARATOR.'home'.DIRECTORY_SEPARATOR.'qrcode?'.$param_url;
                        $qr_url = 'http://wzk.36ve.com/index.php'.DIRECTORY_SEPARATOR.'home'.DIRECTORY_SEPARATOR.'qrcode?'.$param_url;
                        $url = PdUtils::get_qr_code_image_url($qr_url,400,400);
                    }
                    $res_data = [
                        'id' => $signId,
                        'sign_type' => $TCourseSigninInfo['type'],
                        'code' => $TCourseSigninInfo['type']=='signinType.code' ? $url : $TCourseSigninInfo['code']
                    ];
                    $transaction->commit();
                    $result = [
                        'msg' => '发布成功',
                        'ver' => '1.5.0',
                        'data' => $res_data,
                        'code' => '200'
                    ];
                } else {
                    $transaction->rollback();
                    $result = [
                        'msg' => '发布失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '400'
                    ];
                }
            } else {
                $result = [
                    'msg' => '该签到已发布',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    //发布签到验证开始结束时间
    public function CheckClass($class_id,$course_id,$start_time='',$end_time='',$msg=''){
        $class_arr = explode(',', $class_id);
        $sql = '';
        if (!empty($start_time)) {
            if (!empty($end_time)) {
                $sql = "SELECT * FROM `t_course_signin_info` where ((start_time < '$start_time' AND end_time > '$start_time') OR (start_time < '$end_time' and end_time > '$end_time') or (start_time >= '$start_time' and end_time <= '$end_time')) AND del_flag = 0 AND course_id='$course_id';";
            } else {
                $sql = "SELECT * FROM `t_course_signin_info` where (start_time<'$start_time' AND end_time>'$start_time') AND del_flag = 0 AND course_id='$course_id';";
            }
        } else {
            if (!empty($end_time)) {
                $sql = "SELECT * FROM `t_course_signin_info` where (start_time<'$end_time' and end_time>'$end_time') AND del_flag = 0 AND course_id='$course_id';";
            }
        }
        $TCourseSigninInfo = TCourseSigninInfo::findBySql($sql)->asArray()->all();
        if (!empty($TCourseSigninInfo)) {
            $class_exist = [];
            foreach ($TCourseSigninInfo as $value) {
                $class = explode(',', $value['party_id']);
                foreach ($class as $val) {
                    $class_exist[$val] = $val;
                }
            }
            $same = array_intersect($class_exist, $class_arr);
            if (!empty($same)) {
                $result = array(
                    "msg" => '班级签到时间不能重叠',
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '400'
                );
                Yii::$app->end(json_encode($result));
            } else {
                $result = array(
                    "msg" => "班级没有重叠的时间",
                    'code' => '200'
                );
            }
        } else {
            $result = array(
                "msg" => "班级没有重叠的时间",
                'code' => '200'
            );
        }
        return json_encode($result);
    }
    /**
     * 微信小程序课堂教学签到详情学生列表接口
     * @param int  class_id:班级ID course_id:课程ID user_id:用户ID token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-04-14
     * @author: gyq
     */
    public function actionAppSignStudentList(){
        $error      = array();
        $sign_id    = isset($_REQUEST['sign_id']) && !empty($_REQUEST['sign_id']) ? $_REQUEST['sign_id'] : $error=array('签到id不能为空');
        $course_id  = isset($_REQUEST['course_id']) && !empty($_REQUEST['course_id']) ? $_REQUEST['course_id'] : $error=array('课程id不能为空');
        $class_id   = isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : $error=array('班级id不能为空');
        $status     = isset($_REQUEST['status']) && !empty($_REQUEST['status']) ? $_REQUEST['status'] : $error=array('签到状态不能为空');
        $projectId  = isset($_REQUEST['projectId']) && !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[]=array('联盟ID不能为空');
        $pageSize   = !empty($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : '20';
        $page       = !empty($_REQUEST['page']) ? $_REQUEST['page'] : '1';
        $limit      = "limit ".($page-1)*$pageSize.",$pageSize";
        if (!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $class_id = explode(',',$class_id);
            $class_id = implode("','",$class_id);
            $where = '';
            if ($status=='yesOrNo.yes') {
                $where = " AND a.student_status='signinStatus.sign' ";
            } else {
                $where = " AND a.student_status!='signinStatus.sign' ";
            }
            $sign_sql = "SELECT count(*) "
                . "FROM t_course_signin_student a "
                . "LEFT JOIN t_course_member c ON a.user_id = c.user_id and c.course_id='".$course_id."' "
                . "WHERE c.del_flag=0 AND c.class_id IN ('".$class_id."') and a.del_flag=0 AND a.sign_id=:sign_id AND a.student_status='signinStatus.sign' ";
            $sign_num = Yii::$app->db->createCommand($sign_sql)->bindValues([':sign_id'=>$sign_id])->queryScalar();
            $unsign_sql = "SELECT count(*) "
                . "FROM t_course_signin_student a "
                . "LEFT JOIN t_course_member c ON a.user_id = c.user_id and c.course_id='".$course_id."' "
                . "WHERE c.del_flag=0 AND c.class_id IN ('".$class_id."') and a.del_flag=0 AND a.sign_id=:sign_id AND a.student_status!='signinStatus.sign' ";
            $unsign_num = Yii::$app->db->createCommand($unsign_sql)->bindValues([':sign_id'=>$sign_id])->queryScalar();
            //没有过滤删除的班级
            $sql = "SELECT a.id as sign_id,a.user_id,b.pet_name,c.class_id,IFNULL(d.class_name,'默认班级') as class_name,a.signin_time,a.student_status "
                . "FROM t_course_signin_student a "
                . "LEFT JOIN t_base_user_profile b ON a.user_id = b.user_id "
                . "LEFT JOIN t_course_member c ON a.user_id = c.user_id and c.course_id='".$course_id."' "
                . "LEFT JOIN t_base_class d ON c.class_id = d.id "
                . "WHERE c.del_flag=0 AND c.class_id IN ('".$class_id."') and a.del_flag=0 AND a.sign_id=:sign_id $where GROUP BY a.user_id "
                . "ORDER BY a.signin_time DESC,class_name DESC $limit";
            $student = Yii::$app->db->createCommand($sql)->bindValues([':sign_id'=>$sign_id])->queryAll();
            $new_array = array('sign_num'=>$sign_num,'unsign_num'=>$unsign_num,'data'=>$student);
            $result = [
                'msg' => '查询成功',
                'ver' => '1.5.0',
                'data' => $new_array,
                'code' => '200'
            ];
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序结束签到接口
     * @param string token:token userId:用户ID signId：签到ID
     * @return mixed 错误返回json，正确返回json
     * @date: 2020-04-15
     * @author: gyq
     */
    public function actionAppEndSign(){
        $error  = array();
        $userId = isset($_REQUEST['userId']) && !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[]=array('用户ID不能为空');
        $signId = isset($_REQUEST['signId']) && !empty($_REQUEST['signId']) ? $_REQUEST['signId'] : $error[]=array('签到ID不能为空');
        if(!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $time = date('Y-m-d H:i:s');
            $signInfo = \app\models\TCourseSigninInfo::findOne($signId);
            if ($signInfo['end_time']>$time) {
                $signInfo->end_time = $time;
                $signInfo->update_time = $time;
                $signInfo->update_by = $userId;
                if($signInfo->save()){
                    $result = [
                        'msg' => '操作成功',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '200'
                    ];
                } else {
                    $result = [
                        'msg' => '操作失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '400'
                    ];
                }
            } else {
                $result = [
                    'msg' => '签到已结束',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '200'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
}
?>